<?php

namespace cms\modules\v1\models\shop;

use cms\modules\v1\models\Common;
use Codeception\Template\Api;
use common\models\Functions;
use common\models\Status;
use common\services\upload\Qiniu;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int    $id
 * @property string $name
 */
class GoodsCategory extends \common\models\shop\GoodsCategory
{

    public function rules()
    {
        return [
            [['name'],'required','message' => "{attribute}不能为空", 'on' => ['addEdit']],
            [['name'],'filter','filter' => 'trim','on' => ['addEdit']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name' => '账号',
            'tag' => '标签',
            'status' => '状态',
            'list_order' => '排序',
            'is_home' => '首页推荐',
            'back_image' => '分类精选',
            'image' => '图片',
        ];

    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $scenarios = [
            'addEdit' => [
                'name',
                'tag',
                'status',
                'list_order',
                'is_home',
                'icon',
                'back_image',
                'image',
            ],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    public function getList()
    {
        try {
            $list = $this->getAllCategory();
            return Functions::formatRestAPI(0, '', $list);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getTree($goodsId = 0)
    {
        try {
            $goodsId = (int) $goodsId;
            $where['goods_id'] = $goodsId;
            $category = GoodsCategoryRelation::getByWhere($where);
            $category = array_column($category, 'category_id');

            $list = $this->getAllCategoryForTree(0, $category);

            return Functions::formatRestAPI(0, '', $list);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getSpecialTreeMap()
    {
        try {
            #获取第一级
            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $moduleList = static::getByWhere($where, "*", "list_order asc");
            $top = $this->getSubLevel($moduleList, 0);
            $result = [];
            foreach ($top as $v) {
                $result[] = [
                    'id' => $v['id'],
                    'name' => $v['name'],
                    'disabled' => true
                ];
                $subLevel = $this->getSubLevel($moduleList, $v['id']);
                if (!empty($subLevel)) {
                    foreach ($subLevel as $kk => $vv) {
                        $result[] = [
                            "id" => $vv['id'],
                            "name" => "|------" . $vv['name'],
                            'disabled' => false
                        ];
                    }
                    $tmp['children'] = $subLevel;
                }
            }

            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }

    }

    public function getSubLevel($moduleList = [], $parent = 0)
    {
        $result = [];
        foreach ($moduleList as $v) {
            if ($v['parent_id'] == $parent) {
                $result[] = $v;
            }
        }

        return $result;
    }

    public function getAllCategory($parentId = 0)
    {
        $where['parent_id'] = $parentId;
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
        $list = static::getByWhere($where, "*", "list_order asc");
        $result = [];
        if (empty($list)) {
            return null;
        }
        foreach ($list as $v) {
            $tmp = [
                'id' => (int)$v['id'],
                'name' => $v['name'],
                'image' => static::getImages($v['image']),
                'level' => $v['level_num'],
                'order' => (int)$v['list_order'],
                'tag' => $v['tag'],
                'status' => $v['status'],
                'is_home' => $v['is_home'],
            ];
            $children = $this->getAllCategory($v['id']);
            if (!empty($children)) {
                $tmp['children'] = $children;
            }
            $result[] = $tmp;
        }

        return $result;
    }

    public function getAllCategoryForTree($parentId = 0, $category = [])
    {
        $where['parent_id'] = $parentId;
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;

        $list = static::getByWhere($where);
        $result = [];
        if (empty($list)) {
            return null;
        }
        foreach ($list as $v) {
            $tmp = [
                'id' => (int) $v['id'],
                'title' => $v['name'],
                'expand' => true,
                'checked' => in_array($v['id'], $category)
            ];
            $children = $this->getAllCategoryForTree($v['id'], $category);
            if (!empty($children)) {
                $tmp['children'] = $children;
            }
            $result[] = $tmp;
        }
        return $result;
    }

    public function getInfo($id = 0)
    {
        try {
            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('未知信息');
            }
//            $info['image'] = empty($info['image']) ? '' : $this->imageHost . $info['image'];
            $info['imageUrl'] = $info['image'] ? $this->getImages($info['image']) : '';
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $id = Yii::$app->request->post('id',0);
            $parentId = Yii::$app->request->post('parent_id',0);
            $post = Yii::$app->request->post();
            $data = [];
            $data['level_path'] = "0,";
            $data['level_num'] = 1;
            $data['parent_id'] = 0;
            if (!empty($parentId)) {
                $parentInfo = static::getOneInfoById($parentId);
                if (empty($parentInfo)) {
                    throw new Exception('数据异常，请联系开发小哥');
                }
                $data['parent_id'] = $parentId;
                $data['level_path'] = $parentInfo['level_path'] . $parentId . ",";
                $data['level_num'] = $parentInfo['level_num'] + 1;
            }

            if (!empty($id)) {
                //更新操作
                $data = array_merge($data, $this->getSaveData($this->scenario, $post));
                $data['update_time'] = date('Y-m-d H:i:s');
                $info = static::getOneByWhere(['id' => $id]);

                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }
            } else {
                if ($data['level_num'] > 4) {
                    throw new Exception('添加失败，最多支持4级分类');
                }
                //添加操作
                $data = array_merge($data, $this->getSaveData($this->scenario, $post));
                $data['update_time'] = $data['create_time'] = date('Y-m-d H:i:s');
                //如果是上传
                if (isset($_FILES['image'])) {
                    $data['image'] = (new Qiniu()) -> uploadFile('goodsCategory','image');
                }
                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }

            }
            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getCategoryMap() {
        $where['status'] = Status::COMMON_RADIO_YES;
        $where['is_delete'] = Status::COMMON_RADIO_NO;
        $list = static::getByWhere($where,['id','name'],'id ASC');

        $result = [];
        foreach ($list as $v) {
            $result[] = [
                "id" => $v['id'],
                'name' => $v['name']
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }

}
